/**
 * Copyright 2010 MiSSO4J author(s)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sjsso.app.filter;

import static org.sjsso.Constant.*;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.sjsso.app.service.Authentication;
import org.sjsso.model.User;
import org.sjsso.util.PropertyUtil;

public class PolicyAgent implements Filter {
	private static String appid;
	private static String ssosrvurl;
	private static String cburl;
	private static Authentication authService;

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(SESSION_USER);
		String requestUrl = request.getQueryString();
		String uri = request.getRequestURI();
		boolean loggedIn = false;

		if (uri.indexOf("logout") >= 0) {
			loggedIn = true;
		} else if (user != null && authService.isLoggedIn(user)) {
			// User is already login so continue
			loggedIn = true;
		} else if (hasNonce(requestUrl)) {
			user = authService.getUser(request);
			if (user != null) {
				session.setAttribute(SESSION_USER, user);
				loggedIn = true;
			}
		}

		if (loggedIn) {
			chain.doFilter(request, response);
		} else {
			session.invalidate();
			String url = ssosrvurl
					+ "?"
					+ APPID
					+ "="
					+ appid
					+ "&"
					+ CALLBACK_URL
					+ "="
					+ URLEncoder.encode(cburl, "UTF-8")
					+ "&"
					+ PREV_URL
					+ "="
					+ URLEncoder.encode(request.getRequestURL().toString(),
							"UTF-8");
			response.sendRedirect(url);
		}
	}

	private boolean hasNonce(String str) {

		return (str != null && (str.indexOf("nonce") >= 0));
	}

	public void init(FilterConfig config) throws ServletException {
		appid = PropertyUtil.getAppId();
		ssosrvurl = PropertyUtil.getSSOServerUrl();
		cburl = PropertyUtil.getCallbackUrl();
		ServletContext context = config.getServletContext();
		context.setAttribute(APPID, appid);
		context.setAttribute(SSOSRV_URL, ssosrvurl);
		authService = new Authentication(ssosrvurl);
		System.out.println("APP ID= " + appid);
		System.out.println("SSO SRV= " + ssosrvurl);
	}

	public void destroy() {
		//
	}
}
